package com.xiangxiangjd.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xiangxiangjd.bean.*;
import com.xiangxiangjd.bean.vo.ManagementDocx;
import com.xiangxiangjd.controller.helper.$;
import com.xiangxiangjd.mapper.ManagementDateNoMapper;
import com.xiangxiangjd.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiangxiangjd.bean.result.ResultPage;
import com.xiangxiangjd.controller.model.ApiResultModel;

import com.xiangxiangjd.utils.OddNumber;
import com.xiangxiangjd.utils.StringUtilsXiao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 处置批次 服务实现类
 *
 * @author 肖守凯
 * @since 2021-11-23
 */
@Service
public class ManagementDateNoServiceImpl
    extends ServiceImpl<ManagementDateNoMapper, ManagementDateNo>
    implements ManagementDateNoService {

  // 处置的物品
  @Autowired private ManagementGoodsService managementGoodsService;
  @Autowired private GoodsService goodsService;
  @Autowired private UnitService unitService;

  @Autowired private TrUserService trUserService;

  @Autowired private DateNoService dateNoService;

  /**
   * 添加ManagementDateNo
   *
   * @param managementDateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Override
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  public ApiResultModel addManagementDateNo(ManagementDateNo managementDateNo) {

    if (StringUtilsXiao.isBlank(managementDateNo.getGoodsState())) {
      throw new RuntimeException("处置的物品状态不可为 空值");
    }

    // 查询最后一次插入的单号
    String lastOddNumber = baseMapper.getLastOddNumber();
    // 生成新的单号
    String newOddNumber = OddNumber.getOddNumber("CZ", lastOddNumber);
    managementDateNo.setManagementOddNumber(newOddNumber);
    managementDateNo.setManagementState("1");

    if (!this.save(managementDateNo)) {
      return $.error("添加失败");
    }

    // 获取所有需要处置的物品
    List<ManagementGoods> managementGoodsList = managementDateNo.getManagementGoodsList();

    managementGoodsList.forEach(
        o -> {
          if (StringUtilsXiao.isBlank(o.getGoodsId())) {
            throw new RuntimeException("物品id不可为空");
          }
          if (StringUtilsXiao.isBlank(o.getManagementReason())) {
            throw new RuntimeException("处置原因不可为 空值");
          }

          o.setManagementId(managementDateNo.getId());
        });

    // 添加处置的物品
    boolean b = managementGoodsService.saveBatch(managementGoodsList);
    if (!b) {
      throw new RuntimeException("保存失败");
    }

    return $.success("请等待管理员审批！");
  }
  /**
   * 编辑跳转页面的回显数据ManagementDateNo
   *
   * @param id 前端传进的参数
   * @return 返回实体类
   */
  @Override
  public ManagementDateNo selectManagementDateNoByIdManagementDateNo(String id) {
    return this.getById(id);
  }

  /**
   * 编辑ManagementDateNo
   *
   * @param managementDateNo 前端传进的参数
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel editManagementDateNo(ManagementDateNo managementDateNo) {
    if (this.updateById(managementDateNo)) {
      return $.success();
    } else {
      return $.error("编辑失败");
    }
  }
  /**
   * 删除一条ManagementDateNo
   *
   * @param ids 前端传进的ID
   * @return 返回统一信息
   */
  @Override
  public ApiResultModel delManagementDateNos(List ids) {

    int i = baseMapper.deleteBatchIds(ids);

    return $.success(i);
  }

  /**
   * 分页查询ManagementDateNo
   *
   * @param page 页码
   * @param limit 查几条
   * @param managementDateNo 前端传进的参数
   * @return 返回统一分页信息
   */
  @Override
  public ResultPage findManagementDateNoByPage(
      Integer page, Integer limit, ManagementDateNo managementDateNo) {
    Map<String, Object> paramMap = new HashMap<>();
    page = page == null ? 1 : page;
    limit = limit == null ? 20 : limit;

    paramMap.put("page", (page - 1) * limit);
    paramMap.put("limit", limit);
    paramMap.put("managementDateNo", managementDateNo);

    if (!StringUtilsXiao.isBlank(managementDateNo.getCreateTime())) {
      String[] createTime = managementDateNo.getCreateTime().split(",");

      if (createTime[0].equals(createTime[1])) {
        createTime[1] = String.valueOf((Long.valueOf(createTime[1]) + 24 * 60 * 60 * 1000) - 1);
      }
      paramMap.put("createTimeStart", createTime[0]);
      paramMap.put("createTimeEnd", createTime[1]);
    }
    List<ManagementDateNo> list = baseMapper.selectMyPage(paramMap);
    Integer count = baseMapper.countMyPage(paramMap);
    ResultPage<ManagementDateNo> resultPage = new ResultPage<>();
    resultPage.setCode(200);
    resultPage.setCount(count);
    resultPage.setMsg("成功");
    resultPage.setData(list);
    return resultPage;
  }

  /**
   * 审批成功
   *
   * @param managementDateNoId
   * @param
   * @return
   */
  @Transactional(isolation = Isolation.REPEATABLE_READ)
  @Override
  public ApiResultModel managementApproved(
      @RequestParam("managementDateNoId") Integer managementDateNoId, String userId) {

    boolean update1 =
        this.update(
            new LambdaUpdateWrapper<ManagementDateNo>()
                .set(ManagementDateNo::getManagementState, "2")
                .eq(ManagementDateNo::getId, managementDateNoId));

    if (!update1) {
      throw new RuntimeException("失败");
    }

    // 查询该批次和所有要处置的物品
    ManagementDateNo managementDateNo = baseMapper.getByManagementAllGoods(managementDateNoId);

    // 给所有的物品修改状态
    List<ManagementGoods> managementGoodsList = managementDateNo.getManagementGoodsList();
    // 获取所有的id
    //  List<String> collect =
    // managementGoodsList.stream().map(ManagementGoods::getGoodsId).collect(Collectors.toList());

    for (int i = 0; i < managementGoodsList.size(); i++) {

      boolean update =
          goodsService.update(
              new LambdaUpdateWrapper<Goods>()
                  .set(Goods::getUserId, managementDateNo.getGoodsState())
                  .set(Goods::getManagementInfo, managementGoodsList.get(i).getManagementReason())
                  .eq(Goods::getId, managementGoodsList.get(i).getGoodsId())
                  .eq(Goods::getUserId, userId));

      if (!update) {
        throw new RuntimeException("修改 失败 请查看物品是否在自己名下");
      }
    }

    return $.success("审批成功");
  }

  @Override
  public ManagementDateNo getByManagementAllGoods(Integer managementDateNoId) {
    return baseMapper.getByManagementAllGoods(managementDateNoId);
  }

  // 存储状态
  private static final Map<String, String> map=new HashMap<String, String>();

  static {
    map.put("1", "调出");
    map.put("2", "报废");
    map.put("3", "借出");
  }

  @Override
  public Map downDocManagementDateNo(Integer managementDateNoId) {

    List<ManagementDocx> managementDocxList = new ArrayList<>();

    // 查询处置单号详细信息
    ManagementDateNo byManagementAllGoods = getByManagementAllGoods(managementDateNoId);
    if(byManagementAllGoods==null){
      throw new RuntimeException("该处理订单不存在");
    }


    // 处置的航材信息
    List<ManagementGoods> managementGoodsList = byManagementAllGoods.getManagementGoodsList();

    // 序号累计
    int i = 0;

    for (ManagementGoods managementGoods : managementGoodsList) {
      Goods goods = managementGoods.getGoods();
      ManagementDocx managementDocx = new ManagementDocx();
      managementDocx.setSerialNumber(++i);
      managementDocx.setGoodsName(goods.getGoodsName());
      managementDocx.setModel(goods.getModel());
      managementDocx.setCompany(goods.getCompany());
      managementDocx.setNumber(goods.getNumber());
      managementDocx.setPrice(goods.getPrice());

      //查询获取日期
      DateNo dateNo = dateNoService.getById(goods.getDateNoId());
      managementDocx.setPurchaseDate(StringToDate(dateNo.getPurchaseDate()));

      managementDocx.setManagementInfo(managementGoods.getManagementReason());
      managementDocx.setGoodsStateInfo(map.get(byManagementAllGoods.getGoodsState()));

      managementDocxList.add(managementDocx);
    }

    Map map = new HashMap();

    map.put("data", managementDocxList);
    map.put("date", new Date());

    TrUser user = trUserService.getById(byManagementAllGoods.getManagementUserId());

    Unit unit = unitService.getById(user.getUnitId());
    String affiliatedUnits = unit.getUnitName();

    map.put("affiliatedUnits", affiliatedUnits);

    return map;
  }


  private static String StringToDate(String time) {

    Date d = new Date(Long.valueOf(time));

    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

    return sf.format(d);
  }

}
